package com.coflxl.web.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.sagacity.sqltoy.SqlToyContext;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.AbstractDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Autowired
    private Environment env;

    @Bean("primaryDataSource")
    @Primary
    public DataSource primaryDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.jdbc-url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));

        return dataSource;
    }

    @Bean("dynamicDataSource")
    public DynamicDataSource dynamicDataSource(@Autowired DataSource primaryDataSource) {
        Map<Object, Object> targetDataSources = loadTargetDataSources(primaryDataSource);
        return new DynamicDataSource(primaryDataSource, targetDataSources);
    }

    private Map<Object, Object> loadTargetDataSources(DataSource defaultDataSource) {
        Map<Object, Object> result = new HashMap<>();
        try (Connection conn = defaultDataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT * FROM sys_common_db_config WHERE enabled = 1");
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                DruidDataSource ds = new DruidDataSource();
                ds.setDriverClassName(rs.getString("driver_class_name"));
                ds.setUrl(rs.getString("url"));
                ds.setUsername(rs.getString("username"));
                ds.setPassword(rs.getString("password"));
                DynamicDataSourceRegister.addDataSource(rs.getString("id"),ds, getDialect(rs.getString("url")));
                result.put(rs.getString("id"), ds);
            }
        } catch (SQLException e) {
            throw new RuntimeException("加载动态数据源失败", e);
        }
        return result;
    }

    private String getDialect(String jdbcUrl) {
        if (jdbcUrl.contains("mysql")) {
            return "mysql";
        } else if (jdbcUrl.contains("oracle")) {
            return "oracle";
        } else if (jdbcUrl.contains("postgresql")) {
            return "postgresql";
        } else if (jdbcUrl.contains("sql server")) {
            return "sqlserver";
        } else if (jdbcUrl.contains("db2")) {
            return "db2";
        } else if (jdbcUrl.contains("h2")) {
            return "h2";
        } else if (jdbcUrl.contains("derby")) {
            return "derby";
        } else if (jdbcUrl.contains("sqlite")) {
            return "sqlite";
        } else if (jdbcUrl.contains("达梦")) {
            return "dm";
        } else if (jdbcUrl.contains("kingbase")) {
            return "kingbase";
        } else if (jdbcUrl.contains("gbase")) {
            return "gbase";
        } else if (jdbcUrl.contains("oceanbase")) {
            return "oceanbase";
        }
        return "";

    }
}